package com.janyee.powerdroid.http.callback

import android.os.AsyncTask
import android.util.Log
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException

/**
 * Created by kmlixh on 17/5/5.
 * useage:
 * PowerDroid
 */
interface ICallBack<in V,R>:Callback{
    fun transform(response: Response?):R?
    fun workOnBackThread(r: R?,e:Exception?):R?
    fun workOnUiThread(r:R?)
    fun sendProcess(v:V?)
    fun handleProcessOnUiThread(v:V?)
}

abstract class BaseCallBack<V, R> : AsyncTask<Response, V, R>(),ICallBack<V,R>{
    var excuted=false
    var e:Exception?=null
    var call: Call? = null
    fun cancel(){
        if (call==null){
            return
        }
        call!!.cancel()
    }
    override fun doInBackground(vararg response: Response?): R?{
        var res:Response?=null
        if (response!=null){
            res=response[0]
        }
        return workOnBackThread(transform(res),e)
    }

    override fun onPostExecute(result: R) {
        super.onPostExecute(result)
        workOnUiThread(result)
    }
    override fun onProgressUpdate(vararg values: V) {
        handleProcessOnUiThread(values[0])
    }

    override fun sendProcess(v: V?) {
        super.publishProgress(v)
    }
    override fun onFailure(call: Call?, e: IOException?) {
        this.e=e
        excute(null)
    }

    override final fun onResponse(call: Call?, response: Response?) {
        excute(response)
    }
    fun excute( response: Response?){
        if (!excuted){
            excuted=true
            super.execute(response)
        }
    }

}
